from flask import Blueprint, request, jsonify, session
import os
from cozepy import Coze, TokenAuth, Message, ChatEventType, COZE_CN_BASE_URL
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 获取Coze API配置
coze_api_token = os.getenv("COZE_API_TOKEN")
coze_api_base = os.getenv("COZE_API_BASE") or COZE_CN_BASE_URL
coze_bot_id = os.getenv("COZE_BOT_ID")

# 初始化Coze API客户端
coze = Coze(auth=TokenAuth(coze_api_token), base_url=coze_api_base)

# 创建蓝图
cat_chat_bp = Blueprint('cat_chat', __name__)

# 会话ID前缀，用于区分普通聊天和猫咪聊天
CAT_SESSION_PREFIX = "cat_chat_"

@cat_chat_bp.route('/api/cat_chat', methods=['POST'])
def chat_with_cat():
    """处理与小猫的聊天请求"""
    data = request.json
    
    if not data or 'message' not in data:
        return jsonify({
            'success': False,
            'error': '消息不能为空'
        }), 400
    
    user_message = data.get('message', '')
    user_id = data.get('username', request.remote_addr)
    
    # 生成唯一的会话ID，以保持对话上下文连贯
    session_id = f"{CAT_SESSION_PREFIX}{user_id}"
    
    try:
        # 完整回复内容
        full_response = ""
        token_usage = None
        
        # 使用Coze API的流式接口获取回复
        for event in coze.chat.stream(
            bot_id=coze_bot_id,
            user_id=session_id,  # 使用会话ID保持上下文
            additional_messages=[Message.build_user_question_text(user_message)]
        ):
            if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                # 累加回复内容
                if event.message and event.message.content:
                    full_response += event.message.content
            
            # 对话完成事件
            elif event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                token_usage = event.chat.usage.token_count if event.chat and event.chat.usage else None
        
        return jsonify({
            'success': True,
            'message': full_response,
            'token_usage': token_usage
        })
    
    except Exception as e:
        print(f"与小猫聊天时发生错误: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'处理请求时发生错误: {str(e)}'
        }), 500

def init_app(app):
    """注册蓝图到Flask应用"""
    app.register_blueprint(cat_chat_bp)
    print("小猫聊天模块已加载") 